package com.im.app.utils;

import com.im.app.ChatImApplication;
import com.im.app.processor.HttpServiceProcessor;
import org.apache.commons.io.FileUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;

import java.io.File;
import java.util.Objects;

//@Slf4j
public class IpToAddressUtil {

    private static final String IP2REGION_TEMP_DIR = "/home/java/";
    private static Logger logger = LoggerFactory.getLogger(IpToAddressUtil.class);
//    @SneakyThrows
    public static String getRealAddressByIP(String ip) {
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        String dbPath = "";
        String[] obj = new String[0];
        try {
            dbPath = IP2REGION_TEMP_DIR + "ip2region.xdb";
            File file = new File(dbPath);
            if (!file.exists()) {
                return "未知";
//                file = new File(dbPath);
//                FileUtils.copyInputStreamToFile(Objects.requireNonNull(AddressUtils.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.xdb")), file);
            }
            Searcher searcher = Searcher.newWithFileOnly(dbPath);
            String result = searcher.search(ip);
            if (StringUtils.isEmpty(result)) {
                return "未知";
            }

            obj = result.split("\\|");
            searcher.close();
        } catch (Exception e) {
            logger.error("{} 查询地址异常, {}",ip,e.getMessage());
            return "未知";
        }
        StringBuilder sb =new StringBuilder();
        if(!"0".equals(obj[0])){
            sb.append(obj[0]+"-");
        }
        if(!"0".equals(obj[2])){
            sb.append(obj[2]+"-");
        }
        if(!"0".equals(obj[3])){
            sb.append(obj[3]+"-");
        }
        if(!"0".equals(obj[1])){
            sb.append(obj[1]+"-");
        }
        if(!"0".equals(obj[4])){
            sb.append(obj[4]+"-");
        }
        String str= sb.toString();
        str=str.substring(0,str.length()-1);
        return str;
    }


    public static void main(String[] args){
       String address = getRealAddressByIP("27.128.6.152");
       System.out.println(address);
    }

}
